﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using RentIt06WPFClient.UserSession;

namespace RentIt06WPFClient {
    /// <summary>
    /// Interaction logic for AddCredit.xaml
    /// </summary>
    public partial class AddCredit : Window {
        private readonly Account account = Session.User.ReadMyAccount();
        private readonly decimal balance;
        private decimal amountValue;
        public AddCredit(decimal credits) {
            InitializeComponent();
            balance = account.Credit;
            currentBalance.Content = String.Format("${0:0.00}", balance);
            amount.Text = credits.ToString();
            amountValue = credits;
            Show();
        }

        private void amount_TextChanged(object sender, TextChangedEventArgs e) {
            try {
                var newValue = balance + decimal.Parse(amount.Text);
                newBalance.Content = string.Format("${0:0.00}", newValue);
            } catch (Exception) {
            }
        }
        private  void amount_LostFocus(object sender, RoutedEventArgs e) {
            if (!decimal.TryParse(amount.Text, out amountValue))
                amount.Text = "";
        }

        private void back_Click(object sender, RoutedEventArgs e) {
            Close();
        }

        private void submit_Click(object sender, RoutedEventArgs e) {
            var ccard = new CreditCardInformations();
            try {
                ccard.CardNumber = long.Parse(creditcardNumber.Text);
                ccard.ExpirationMonth = expirationDate.SelectedDate.Value.Month;
                ccard.ExpirationYear = expirationDate.SelectedDate.Value.Year;
            } catch (Exception) {
                MessageBox.Show("Please enter proper credit card information", "Creditcard info required",
                                MessageBoxButton.OK, MessageBoxImage.Asterisk);
                return;
            }
            Session.User.AddCredit(amountValue, ccard , false);
            Close();
        }
    }
}
